'use strict';

const pathToRegexp = require('path-to-regexp');

const toPathMatch = (pattern, path) => {
  if (typeof pattern === 'string') {
    const reg = pathToRegexp(pattern, [], { end: false });
    if (reg.global) reg.lastIndex = 0;
    return reg.test(path);
  }
  if (Array.isArray(pattern)) {
    const matchs = pattern.map(p => toPathMatch(p, path));
    return matchs.some(match => match === true);
  }
};

module.exports = (options, app) => {
  const { redis } = app;

  return async ctx => {
    const { user } = ctx;
    const data = await redis.get(user.id);
    const { permission } = JSON.parse(data);
    // console.log('=====permission====', permission);
    const pattern = permission.map(item => '/api' + item.url);
    const matched = toPathMatch(pattern, ctx.path);
    if (matched) {
      return;
    }
    ctx.throw(403);
  };
};
